package Review.Linklist;

public class MyListNode {
       static class ListNode{
           int val;
           ListNode next;
           ListNode(int val){
               this.val = val;
           }
       }
        private int size;
        private ListNode head;
        //初始化链表
        public MyListNode(){
            this.size = 0;
            this.head=new ListNode(0);
        }
        //获取第index个节点的数值
        public int get(int index){
            if(index<0 || index>=size){
                return -1;
            }
            ListNode cur=head;
            for(int i=0;i<=index;i++){
                cur=cur.next;
            }
            return cur.val;
        }
        //在头部添加值
        public void addAtHead(int val){
            //head是虚拟节点，不存在值
            ListNode newNode=new ListNode(val);
            newNode.next=head.next;
            head.next=newNode;
            size++;
        }
        public void addAtTail(int val){
            ListNode newNode=new ListNode(val);
            ListNode cur=head;
            while(cur.next!=null){
                cur=cur.next;
            }
            cur.next=newNode;
            size++;
        }
        //在第index个节点前添加一个新的节点
    public void addAtIndex(int index,int val){
            if(index<0 || index>=size){
                return;
            }
            ListNode newNode=new ListNode(val);
            ListNode pre=head;
            //插入结点的前驱
            for(int i=0;i<=index;i++){
                pre=pre.next;
            }
            newNode.next=pre.next;
            pre.next=newNode;
            size++;
    }
    public void removeAtIndex(int index){
            if(index<0 || index>=size){
                return;
            }
            //找到删除结点的前一个
            ListNode pre=head;
            for(int i=0;i<=index;i++){
                pre=pre.next;
            }
            //删除节点
            pre.next=pre.next.next;
            size--;
    }


}
